// electron/controller/CodeController.ts
import CodeService from '../service/CodeService';
import type { IpcMainEvent } from 'electron';
import { dialog, BrowserWindow } from 'electron';
import fs from 'fs/promises';
import log from 'electron-log/node';

class CodeController {
  /**
   * 保存代码到内存缓存
   * @param event IpcMainEvent 事件对象
   * @param code 代码内容
   */
  saveCode(event: IpcMainEvent, code: string) {
    const id = event.sender.id;
    CodeService.saveCode(id, code);
    // 通知渲染进程保存结果
    event.sender.send('code:save:result', { success: true });
  }

  /**
   * 获取当前窗口的代码内容
   * @param event IpcMainEvent 事件对象
   */
  getCode(event: IpcMainEvent) {
    const id = event.sender.id;
    // 获取缓存中的代码内容
    const code = CodeService.getCode(id) || '';
    // 返回给渲染进程
    event.sender.send('code:get:result', code);
  }

  /**
   * 将代码保存到指定文件路径
   * @param event IpcMainEvent 事件对象
   * @param code
   * @param filePath 文件路径
   */
  saveCodeToFile(event: IpcMainEvent, code: string, filePath: string) {
    const id = event.sender.id;
    try {
      CodeService.saveCode(id, code);

      CodeService.saveCodeToFile(id, filePath);
      // 通知渲染进程保存成功
      event.sender.send('code:save:file:result', {
        success: true,
        path: filePath,
      });
    } catch (error) {
      // 通知渲染进程保存失败
      event.sender.send('code:save:file:result', {
        success: false,
        message: (error as Error).message,
      });
    }
  }

  /**
   * 清理当前窗口的代码缓存
   * @param event IpcMainEvent 事件对象
   */
  dispose(event: IpcMainEvent) {
    const id = event.sender.id;
    CodeService.dispose(id);
  }

  /**
   * 用户手动选择文件保存代码
   * @param event IpcMainEvent 事件对象
   */
  async saveCodeToUserSelectedFile(event: IpcMainEvent) {
    const id = event.sender.id;
    // 获取缓存中的代码
    const code = CodeService.getCode(id);
    if (!code) {
      // 未找到代码缓存，通知渲染进程
      return event.sender.send('code:save:user-file:result', {
        success: false,
        message: '未找到代码缓存',
      });
    }

    const { filePath, canceled } = await dialog.showSaveDialog(
      BrowserWindow.getFocusedWindow()!,
      {
        title: '保存 Python 文件',
        defaultPath: 'script.py',
        filters: [{ name: 'Python', extensions: ['py'] }],
      },
    );

    if (canceled || !filePath) {
      // 用户取消保存
      return event.sender.send('code:save:user-file:result', {
        success: false,
        canceled: true,
      });
    }

    try {
      // 写入文件
      await fs.writeFile(filePath, code, 'utf-8');
      event.sender.send('code:save:user-file:result', { success: true });
    } catch (error) {
      // 写入失败
      event.sender.send('code:save:user-file:result', {
        success: false,
        message: (error as Error).message,
      });
    }
  }

  /**
   * 用户选择文件加载到编辑器
   * @param event IpcMainEvent 事件对象
   */
  async loadCodeFromFile(event: IpcMainEvent) {
    // 弹出打开文件对话框
    const { filePaths, canceled } = await dialog.showOpenDialog(
      BrowserWindow.getFocusedWindow()!,
      {
        title: '打开 Python 文件',
        filters: [{ name: 'Python', extensions: ['py'] }],
        properties: ['openFile'],
      },
    );

    if (canceled || filePaths.length === 0) {
      // 用户取消打开
      return event.sender.send('code:load:file:result', {
        success: false,
        canceled: true,
      });
    }

    try {
      // 读取文件内容
      const content = await fs.readFile(filePaths[0], 'utf-8');
      event.sender.send('code:load:file:result', { success: true, content });
    } catch (error) {
      // 读取失败
      event.sender.send('code:load:file:result', {
        success: false,
        message: (error as Error).message,
      });
    }
  }
}

export default new CodeController();
